//本地OS随机bind
#include <iostream>

#include <string>
#include <cstring>
#include <errno.h>

#include "Log.hpp"
#include "Comm.hpp"

#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Usage(std::string&& str)
{
    std::cout << "格式: " << str << " serverip serverport" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return usage_err;
    }
    //1.创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        lg.LogMessage(Error, "create sockfd failed, errno: %d, %s\n", errno, strerror(errno));
        return sockfd_err;
    }

    //2.自动bind一个随机的当前不被使用的端口号
    //...

    //配置服务器地址信息(服务器网络端点)
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(argv[1]);
    server.sin_port = htons(std::stoi(argv[2]));

    while(1)
    {
        std::string str;
        std::cout << "输入需要发送的内容" << std::endl;
        getline(std::cin, str);
        ssize_t n = sendto(sockfd, str.c_str(), str.size(), 0, (struct sockaddr*)&server, sizeof server);
        if(n > 0) //发出去了
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len;
            int m = recvfrom(sockfd, buffer, 1023, 0, (struct sockaddr*)&peer, &len);
            if(m > 0)
            {
                buffer[m] = 0;
                std::cout << "server: " << buffer << std::endl;
            }
            else
                break;
        }
        else break;
    }
    return 0;
}